import { t } from 'i18next'
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { Select, Button, InnerInputRef, Message, TriggerInstance } from '@kedacom/react-next'
import { StyledWrap, StyledVmpSelectItem } from './style'
import { defaultPlan, PlanEntity, RevertPlanEntity } from './interface'
import { useCreateContentStore } from '../../../store'
import { useMeetingTVWallStore } from '../store'
import shallow from 'zustand/shallow'
import Alert, { Confirm } from '@/components/Alert'
// import { allVmpStyleData } from '../VmpView/interface'
import {
	fetchDeleteTvwallPlan,
	fetchGetTvwallPlanDetail,
	fetchGetTvwallPlanList,
	fetchSaveTvwallPlan,
	fetchUpdateTvwallPlan,
} from '@/api/create/tvwall'
import { useKdPreSettingDialogStore } from '../../../components/KdPreSettingDialog/store'
import { clearCashData, getTvwallPlanParam, setInitCashData } from '../store.combine'
export interface VmpPlanProps {
	disabled?: boolean
	getVmpParam: () => any | null
}
export interface PlanRef {
	getValue: () => RevertPlanEntity | null
}
const TvwallPlan = forwardRef((props: VmpPlanProps, ref: React.Ref<PlanRef>) => {
	/*
	export interface TriggerInstance {
		/** 浮层所在容器，被包裹的元素 
		root: HTMLElement;
		/** 浮层 
		overlay: HTMLElement;
		/** 打开 
		open: () => void;
		/** 关闭 
		close: () => void;
		/** 更新位置 
		updatePosition: () => void;
	}

	# selectRef的使用
	selectRef.current?.close()

	# 讲解
	<TriggerInstance> 是一个泛型参数，它告诉 TypeScript 编译器 selectRef.current 应该具有 TriggerInstance 接口的类型。
	这意味着 selectRef.current 将被推断为 TriggerInstance 类型，并且你可以访问 TriggerInstance 接口中定义的属性和方法。

	TriggerInstance 接口定义了以下内容：

	root: 一个 HTMLElement，表示浮层所在容器，被包裹的元素。
	overlay: 一个 HTMLElement，表示浮层本身。
	open: 一个函数，当调用时会打开浮层。
	close: 一个函数，当调用时会关闭浮层。
	updatePosition: 一个函数，用于更新浮层的位置。

	因此，当你使用 selectRef 时，例如：

	selectRef.current.open(); // 正确使用，因为 TriggerInstance 接口定义了 open 方法
	TypeScript 编译器会知道 selectRef.current 是一个可能包含 open 方法的对象，并且在你尝试调用这个方法时不会报错。

	总结来说，useRef<TriggerInstance>(null) 中的 <TriggerInstance> 是一个TypeScript泛型，
	用于为 useRef 的 .current 属性提供类型信息，确保在使用 selectRef 时能够享受到类型安全和IDE的智能提示功能。

	*/
	const selectRef = useRef<TriggerInstance>(null)
	/**预案id*/
	// const [planValue, setPlanValue] = useState('0')
	const { _name, update, tvwallPlanValue, planOptions, used_style_map, enable, initData } = useMeetingTVWallStore(
		(state) => ({
			planOptions: state.planOptions,
			_name: state.name,
			tvwallPlanName: state.tvwallPlanName,
			tvwallPlanValue: state.tvwallPlanValue,
			update: state.update,
			needUpdate: state.needUpdate,
			used_style_map: state.used_style_map,
			enable: state.enable,
			mode: state.mode,
			show_mt_name: state.show_mt_name,
			initData: state.initData,
		}),
		shallow
	)
	const { preKey, isTemplate, _container } = useCreateContentStore(
		(state) => ({ preKey: state.preKey, isTemplate: state.isTemplate, _container: state._container }),
		shallow
	)

	const { disabled } = props

	useImperativeHandle(ref, () => ({
		getValue() {
			return planOptions.find((item) => item.value === tvwallPlanValue) ?? null
		},
	}))
	useEffect(() => {
		getTvwallPlanList()
	}, [])
	useEffect(() => {
		let _item = planOptions.find((item) => item.label === _name)
		update({ tvwallPlanValue: _item?.value ?? '0' })
	}, [_name, planOptions])
	/**获取电视墙预案列表*/
	const getTvwallPlanList = async () => {
		const plan_arr = await fetchGetTvwallPlanList(preKey, isTemplate)
		if (plan_arr && plan_arr.success) {
			/**转换预案数据*/
			let arr: RevertPlanEntity[] = revert_plan_get_paln_option(plan_arr.data)
			/**赋值预案列表*/
			update({ planOptions: arr })
		}
	}
	/**转换预案数据(处理成为预案下拉列表)*/
	const revert_plan_get_paln_option = (plan_source?: Array<PlanEntity>): Array<RevertPlanEntity> => {
		let arr: RevertPlanEntity[] = []
		if (plan_source) {
			arr = plan_source.map((item) => {
				return {
					label: item.name,
					value: item.id,
				}
			})
		}
		arr.unshift(defaultPlan)
		return arr
	}
	//载入预案
	const changePlan = async (id: string) => {
		if (id === '0') {
			update({ name: '' })
			clearCashData()
			return
		}
		fetchGetTvwallPlanDetail(preKey, isTemplate, id).then((res) => {
			if (res.success) {
				update({ tvwallPlanValue: id })
				initData(res)
			}
		})
	}
	//更新预案
	const updatePlan = async (name: string, data: { label: string; value: string }) => {
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const _params = getTvwallPlanParam()
		let params = Object.assign({}, _params, { name: name })
		const res = await fetchUpdateTvwallPlan(preKey, isTemplate, data.value, params)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name })
			getTvwallPlanList()
		} else {
			Alert(res.description)
		}
	}
	/**保存预案*/
	const savePlan = async (name: string) => {
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const _params = getTvwallPlanParam()
		let params = Object.assign({}, _params, { name: name })
		const res = await fetchSaveTvwallPlan(preKey, isTemplate, params)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name })
			getTvwallPlanList()
		} else {
			Alert(res.description)
		}
	}

	const openDialog = () => {
		if (!enable) {
			return false
		}
		if (used_style_map.length === 0) {
			Alert(t('请选择风格'))
			return
		}
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const url = isTemplate
			? `/meetings/${preKey}/pretvwalls?count=0`
			: `/personal_templates/${preKey}/pretvwalls?count=0`
		let _name = tvwallPlanValue === '0' ? '' : planOptions.find((item) => item.value === tvwallPlanValue)?.label
		useKdPreSettingDialogStore.setState({
			isOpen: true,
			dialogTitle: t('保存为预案'),
			loadUrl: url,
			name: _name,
			self_save: savePlan,
			self_over: updatePlan,
			type: 'tvwall',
		})
	}
	/**删除预案 */
	const deletePlan = async (item: { label: string; value: string }) => {
		let _plan_option = planOptions.filter((v) => item.value !== v.value)
		const isTemplate = useCreateContentStore.getState().isTemplate
		const preKey = useCreateContentStore.getState().preKey
		Confirm(t('是否确定删除{{name}}？', { name: item.label }), async () => {
			const res = await fetchDeleteTvwallPlan(preKey, isTemplate, item.value)
			if (res.success) {
				update({ name: t('不使用预案'), planOptions: _plan_option, planValue: '0' })
			} else {
				Alert(res.description)
			}
		})
	}
	return (
		<StyledWrap className="mcc-vmp-plan-wrap">
			<div className="mcc_vmp_plan_option">
				<Select
					container={() => _container}
					ref={selectRef}
					width={130}
					panelLineHeight={25}
					options={planOptions}
					value={tvwallPlanValue}
					disabled={disabled}
					optionRender={(option, selected) => {
						return (
							<StyledVmpSelectItem
								className={selected ? 'selected' : ''}
								onClick={(e) => {
									e.stopPropagation()
									selectRef.current?.close()
									changePlan(option.value)
								}}
							>
								<span className="select-icon"></span>
								<span className="name">{option.label}</span>
								{option.value !== '0' && (
									<span
										className="delete-icon"
										onClick={(e) => {
											e.stopPropagation()
											deletePlan(option as { label: string; value: string })
										}}
									></span>
								)}
							</StyledVmpSelectItem>
						)
					}}
				/>
				<Button className="savePlan" onClick={openDialog}>
					{t('保存为预案')}
				</Button>
			</div>
		</StyledWrap>
	)
})
export default TvwallPlan
